<?php
require 'db.php'; // 包含数据库连接
require 'vendor/autoload.php'; // 引入 Composer 自动加载器
include_once 'secret/jwt.php';

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

if (!isset($_COOKIE['token'])) {
    header('Location: index.php');
    exit();
}

$jwt = $_COOKIE['token'];

try {
    $decoded = JWT::decode($jwt, new Key($secretKey, 'HS256'));
    $username = $decoded->data->username;
    $role = $decoded->data->role;
    $user_id = $decoded->data->id;
} catch (Exception $e) {
    echo json_encode([
        'error' => '访问被拒绝: ' . $e->getMessage()
    ]);
    exit();
}
// 获取评论内容和文章ID
if (!isset($_POST['article_id'], $_POST['comment'])) {
    echo json_encode(['error' => '缺少必要参数']);
    exit();
}

$article_id = $_POST['article_id'];
$comment = $_POST['comment'];

// 检查是否提供了文章ID
if (!$article_id) {
    echo json_encode(['error' => '未提供文章ID']);
    exit();
}

// 将评论保存到数据库中
$stmt = $conn->prepare("INSERT INTO comments (article_id, commenter,commenter_id, comment) VALUES (?, ?, ?, ?)");
$stmt->bind_param("isis", $article_id, $username, $user_id, $comment);

if ($stmt->execute()) {
    echo json_encode(['success' => true]);
} else {
    echo json_encode(['error' => '提交评论失败']);
}

$stmt->close();
$conn->close();
?>
